package com.example.jt_manager_service;

import com.example.jt_manager_mapper.ContentCategoryMapper;
import com.example.jt_manager_mapper.ContentMapper;
import com.example.jt_manager_pojo.Content;
import com.example.jt_manager_pojo.ContentCategory;
import com.example.jt_manager_pojo.ContentCategoryExample;
import com.example.jt_manager_pojo.ContentExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    ContentCategoryMapper contentCategoryMapper;
    @Autowired
    ContentMapper contentMapper;

    @Override
    public List<ContentCategory> queryCatById(long id) {
        ContentCategoryExample example = new ContentCategoryExample();
        example.createCriteria().andStatusEqualTo(1).andParentIdEqualTo(id);
        return contentCategoryMapper.selectByExample(example);
    }

    @Override
    public void addCategory(ContentCategory contentCategory,long id) {
        contentCategoryMapper.insertSelective(contentCategory);
        setParent(id,true);
    }

    @Override
    public int setParent(long id,boolean isParent) {
        ContentCategory contentCategory = new ContentCategory();
        contentCategory.setId(id);
        contentCategory.setIsParent(isParent);
        return contentCategoryMapper.updateByPrimaryKeySelective(contentCategory);
    }

    @Override
    public void delCategory(long id, long parentId) {
        contentCategoryMapper.deleteByPrimaryKey(id);
        if(queryCatById(parentId).size()==0){
            setParent(parentId,false);
        }
    }

    @Override
    public void updateNameById(long id, String name) {
        ContentCategory contentCategory =new ContentCategory();
        contentCategory.setId(id);
        contentCategory.setName(name);
        contentCategoryMapper.updateByPrimaryKeySelective(contentCategory);
    }

    @Override
    public PageInfo<Content> queryList(long categoryId, int page, int size) {
        PageHelper.startPage(page,size);
        ContentExample example = new ContentExample();
        example.createCriteria().andCategoryIdEqualTo(categoryId);
        List<Content> list = contentMapper.selectByExample(example);
        PageInfo<Content> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void updateContent(Content content) {
        contentMapper.updateByPrimaryKeySelective(content);
    }

    @Override
    public void deleteContentsByIds(List<Long> ids) {
        ContentExample example =new ContentExample();
        example.createCriteria().andIdIn(ids);
        contentMapper.deleteByExample(example);
    }

    @Override
    public void insertContent(Content content) {
        contentMapper.insert(content);
    }

}
